package org.example.algorithm.matrix;

public class RotateSolution {

    //借助辅助矩阵
    public void rotate2(int[][] matrix) {
        if (matrix.length == 0 || (matrix.length == 1 && matrix[0].length == 1)) {
            return;
        }
        int row = matrix.length;
        int col = matrix[0].length;
        if (row != col) {
            System.out.println("行与列不相等，无法原地旋转");
            return;
        }
        int[][] matrixNew = new int[row][row];
        for (int i=0;i<row;i++) {
            for (int j=0;j<row;j++) {
                matrixNew[j][row-i-1] = matrix[i][j];
            }
        }
        for (int i=0;i<row;i++) {
            for (int j=0;j<row;j++) {
                matrix[i][j] = matrixNew[i][j];
            }
        }
    }

    //先上下交换，再沿对角线交换
    public void rotate3(int[][] matrix) {
        if (matrix.length == 0 || (matrix.length == 1 && matrix[0].length == 1)) {
            return;
        }
        int row = matrix.length;
        int col = matrix[0].length;
        if (row != col) {
            System.out.println("行与列不相等，无法原地旋转");
            return;
        }
        //上下交换
        for (int i=0;i<row/2;i++) {
            for (int j=0;j<row;j++) {
                int temp = matrix[i][j];
                matrix[i][j] = matrix[row-i-1][j];
                matrix[row-i-1][j] = temp;
            }
        }
        //沿对角线交换
        for (int i=0;i<row;i++) {
            for (int j=i+1;j<row;j++) {
                int temp = matrix[i][j];
                matrix[i][j] = matrix[j][i];
                matrix[j][i] = temp;
            }
        }
    }

    //原地旋转
    //原地旋转
    public void rotate(int[][] matrix) {
        if (matrix.length == 0 || (matrix.length == 1 && matrix[0].length == 1)) {
            return;
        }
        int row = matrix.length;
        int col = matrix[0].length;
        if (row != col) {
            System.out.println("行与列不相等，无法原地旋转");
            return;
        }
        int loopRow = row / 2;
        int loopCol = (row - 1) / 2;
        for (int i=0;i<loopRow;i++) {
            for (int j=0;j<=loopCol;j++) {
                int temp = matrix[i][j];
                matrix[i][j] = matrix[row-j-1][i];
                matrix[row-j-1][i] = matrix[row-i-1][row-j-1];
                matrix[row-i-1][row-j-1] = matrix[j][row-i-1];
                matrix[j][row-i-1] = temp;
            }
        }
    }
}
